package com.yjhb.android.sbz.mvp.task;

import android.text.TextUtils;

import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.google.gson.Gson;
import com.yjhb.android.sbz.BuildConfig;
import com.yjhb.android.sbz.entity.AddTask;
import com.yjhb.android.sbz.entity.CheckEntity;
import com.yjhb.android.sbz.entity.Comment;
import com.yjhb.android.sbz.entity.TaskSubmit;
import com.yjhb.android.sbz.http.HttpObserver;
import com.yjhb.android.sbz.http.HttpTool;
import com.yjhb.android.sbz.http.UploadTool;
import com.yjhb.android.sbz.manager.OSSManager;
import com.yjhb.android.sbz.mvp.ConventionPresenter;
import com.yjhb.android.sbz.tool.DataSaveTool;
import com.yjhb.android.sbz.tool.Tool;
import com.jojo.android.zxlib.interfaces.Callback;
import com.jojo.android.zxlib.tool.ZxLogTool;

import java.io.File;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 创建者 zx
 * 创建时间 2020/12/1 14:11
 */
public class DetailsPresenter extends ConventionPresenter<DetailsView> {
    private final String TAG = "DetailsPresenter";

    public DetailsPresenter(DetailsView detailsView) {
        super(detailsView);
    }

    @Override
    protected void onDestroy() {

    }

    public void submitTask(final Integer taskId, final List<TaskSubmit> submits, Integer reSubmit) {
        if (view != null) {
            view.onWait();
        }
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                for (TaskSubmit step : submits) {
                    if (step.isImg()) {
                        e.onNext("上传图片:" + step.getContent());
                        //如果图片为null,则直接返回
                        if (TextUtils.isEmpty(step.getContent())) {
                            e.onError(new Throwable(step.getContent() + ": 图片不存在，请重新选择。"));
                            return;
                        }
                        //如果是http开始的字符串，代表已经上传成功，则跳过
                        if (step.getContent().startsWith("http")) continue;

                        File file = new File(step.getContent());
                        //压缩图片
                        File img = Tool.compressImage(file, false);

                        //将图片上传到文件服务器，如果是体验服务器和正式服上传到release文件夹，
                        //否则上传到test文件夹
                        String dir = null;
                        switch (DataSaveTool.getHost()) {
                            case BuildConfig.ServerURL_RELEASE:
                            case BuildConfig.ServerURL_ALPHA:
                                dir = "imgV4/release/taskSubmit";
                                break;
                            default:
                                dir = "imgV4/test/taskSubmit";
                        }
                        PutObjectResult result = UploadTool.OSSUploadFile(img.getAbsolutePath(),
                                dir,
                                img.getName(), new Callback<Long[]>() {
                                    @Override
                                    public void callback(Long[] longs) {

                                    }
                                });
                        if (result == null) {
                            e.onError(new Throwable("图片上传失败，请重试！"));
                            return;
                        }
                        if (result.getStatusCode() != 200) {
                            e.onError(new Throwable("图片上传失败，错误码：" + result.getStatusCode() + " 请重试！"));
                            return;
                        }
                        step.setContent(OSSManager.getUrl(dir, img.getName()));
                    }
                }
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io()) //在IO线程执行网路请求
                .observeOn(AndroidSchedulers.mainThread()) //在UI线程得到数据
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String addTask) {
                        if (view != null) {
                            view.uploading();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ZxLogTool.err(e);
                        if (view != null) {
                            view.onFailure(-2, e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {
                        try {
                            if (view != null) {
                                view.uploadSuccess();
                            }
                            HttpTool.request(model.submitTask(taskId, new Gson().toJson(submits), reSubmit), new HttpObserver<Object>() {
                                @Override
                                public void onResult(Object data) {
                                    if (view != null) {
                                        view.submitSuccess();
                                    }
                                }

                                @Override
                                public void onError(int code, String msg) {
                                    if (view != null) {
                                        view.onFailure(code, msg);
                                    }
                                }
                            });
                        } catch (Exception e) {
                            ZxLogTool.err(e);
                        }


                    }
                });
    }


    public void getPutValue(Integer orderId) {
        if (view != null) {
            view.onWait();
        }
        HttpTool.request(model.getOrderDetail(orderId), new HttpObserver<CheckEntity>() {
            @Override
            public void onResult(CheckEntity data) {
                if (view != null) {
                    view.onPutValue(data);
                }
            }

            @Override
            public void onError(int code, String msg) {
                if (view != null) {
                    view.onPutValue(null);
                }
            }
        });
    }


    /**
     * 任务详情
     *
     * @param taskId
     */
    public void getDetails(String taskId) {
        if (view != null) {
            view.onWait();
        }
        HttpTool.request(model.taskDetail(taskId), new HttpObserver<AddTask>() {
            @Override
            public void onResult(AddTask data) {
                if (view != null) {
                    view.onSuccess(data);
                }
            }

            @Override
            public void onError(int code, String msg) {
                if (view != null) {
                    view.onFailure(code, msg);
                }
            }
        });
    }


    /**
     * 切换任务
     */
    public void another(String taskId, Integer index) {
        if (view != null) {
            view.onWait();
        }
        HttpTool.request(model.randomTask(taskId, index), new HttpObserver<AddTask>() {
            @Override
            public void onResult(AddTask data) {
                if (view != null) {
                    view.onSuccess(data);
                }
            }

            @Override
            public void onError(int code, String msg) {
                if (view != null) {
                    view.onFailure(code, msg);
                }
            }
        });
    }


    /**
     * 报名
     *
     * @param taskId
     */
    public void fetch(String taskId) {
        if (view != null) {
            view.onWait();
        }
        HttpTool.request(model.fetch(taskId), new HttpObserver<String>() {
            @Override
            public void onResult(String data) {
                if (view != null) {
                    view.signSuccess();
                }
            }

            @Override
            public void onError(int code, String msg) {
                if (view != null) {
                    view.onFailure(code, msg);
                }
            }
        });
    }

    /**
     * 报名状态检测
     */
    public void check(String taskId) {
        HttpTool.request(model.fetchCheck(taskId), new HttpObserver<Integer>() {
            @Override
            public void onResult(Integer data) {
                if (view != null) {
                    view.check(data);
                }
            }

            @Override
            public void onError(int code, String msg) {
                if (view != null) {
                    view.check(-2);
                }
            }
        });
    }


    /**
     * 获取最后提交的信息
     *
     * @param taskId
     */
    public void lastSubmitOrder(String taskId) {
        HttpTool.request(model.lastSubmitOrder(taskId), new HttpObserver<CheckEntity>() {
            @Override
            public void onResult(CheckEntity data) {
                if (view != null) {
                    view.onPutValue(data);
                }
            }

            @Override
            public void onError(int code, String msg) {
                if (view != null) {
//                    view.onFailure(co);
                }
            }
        });
    }

    public void checkOrderByTaskName(String taskId) {
        HttpTool.request(model.checkOrderByTaskName(taskId), new HttpObserver<Integer>() {
            @Override
            public void onResult(Integer data) {
                if (view != null && data != null) {
                    view.checkOrderByTaskName(data);
                }
            }

            @Override
            public void onError(int code, String msg) {

            }
        });
    }


    /**
     * 评论
     *
     * @param taskId
     * @param size
     * @param current
     */
    public void commentList(String taskId, int size, int current) {
        HttpTool.request(model.commentList(taskId, size, current), new HttpObserver<List<Comment>>() {
            @Override
            public void onResult(List<Comment> data) {
                if (view != null) {
                    view.onLoadComments(data);
                }
            }

            @Override
            public void onError(int code, String msg) {
                ZxLogTool.e(msg);
            }
        });
    }

}
